package com.action.app_qrcode;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

import com.QRcodeBuilder.CreateQr;
import com.QRcodeBuilder.NetQrPCEntity;
import com.QRcodeBuilder.NetQrVo;
import com.dataProcess.NetConnect;
import com.dataProcess.VerifyResou;
import com.enetiy.Area;
import com.enetiy.Areaip;
import com.enetiy.Balance;
import com.enetiy.Binding;
import com.enetiy.Comboinfo;
import com.enetiy.Keeptime;
import com.enetiy.Useraccount;
import com.enetiy.Userinfo;
import com.enetiy.Users;
import com.operation.NET;
import com.service.AreaIpService;
import com.service.AreaService;
import com.service.AreainfoService;
import com.service.AreausbleService;
import com.service.BindingService;
import com.service.ComboService;
import com.service.DealService;
import com.service.FilterService;
import com.service.MapService;
import com.service.NetLinkService;
import com.service.UseraccountService;
import com.service.UserinfoService;
import com.util.DataUtil;
import com.util.Log4gUtil;
import com.util.NetTimeUtil;
import com.util.Verify;

public class PCNetqrAction {
	private String params;
	private int siteAreaid;
	private String sessionid;
	private String mac;
	private String ip;
	private int userid;
	
	private AreaService areaService;
	private UserinfoService userinfoService;
	private ComboService comboService;
	private AreainfoService areainfoService;
	private BindingService bindingService;
	private AreausbleService areausbleService;
	private AreaIpService areaIpService;
	private UseraccountService useraccountService;
	private NetLinkService netLinkService;
	private MapService mapService;
	private DealService dealService;
	
	private int planTime;
	private String apMac;
	private String NF_callid;
	private String token;
	private String QRType;

	
	/**
	 * 生成二维码内容  >Nf045
	 */
	public void createNetQr(){
		Log4gUtil.getLog().info("createNetQr-进入PC二维码生成-数据:"+params);
		if(params!=null&&!params.equals("")){
			 JSONObject dataParser = DataUtil.dataParser(params);
			 if(dataParser.has("ip"))
				ip =  dataParser.getString("ip");
			 if(dataParser.has("mac"))
				mac =  dataParser.getString("mac");
			 if(dataParser.has("QRType"))
				QRType =  dataParser.getString("QRType");
			 if(dataParser.has("siteAreaid"))
				siteAreaid = dataParser.getInt("siteAreaid");
		}
			HttpServletResponse response = ServletActionContext.getResponse();
			PrintWriter out =null;
			net.sf.json.JSONObject sendJson = DataUtil.sendJson();
			try {
				out = response.getWriter();
				//生成二维码
				CreateQr createQr = new CreateQr();
				boolean judge = createQr.createPCNetQr(ip,mac,siteAreaid,"no",QRType);
				//发送内容
				if(judge){
					sendJson.put("code", 1);
					sendJson.put("text",createQr.text);
					sendJson.put("sessionid", createQr.sessionid);
				}else{
					sendJson.put("code", 0);
					sendJson.put("reason", 3);
					sendJson.put("msg", "数据异常");
				}
		} catch (Exception e) {
			sendJson.put("code", -1);
			sendJson.put("msg", "服务器异常");
			e.printStackTrace();
		}
		//发送
		out.print(sendJson);
		Log4gUtil.getLog().info("createNetQr-输出PC二维码生成-数据:"+sendJson.toString());
	}
	
	/**
	 * 二维码扫描检查登录(长轮循) >Nf046
	 * @return
	 */
	public void  checkNetQr(){
		Log4gUtil.getLog().info("checkNetQr-进入PC二维码扫描检查登录-数据:"+params);
		if(params!=null&&!params.equals("")){
			 JSONObject dataParser = DataUtil.dataParser(params);
			 if(dataParser.has("sessionid"))
				sessionid =  dataParser.getString("sessionid");
		 }
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out =null;
		net.sf.json.JSONObject sendJson = DataUtil.sendJson();
		try {
			//进接口时间
			long inTime = new Date().getTime();
			//本次进接口轮循时间是否失效
	        Boolean bool = true;
	        
	        boolean fig = false;
	        NetQrVo netQrVo = NetQrVo.getNetQrVo();
	        while (bool) {
	            	out = response.getWriter();
	                Thread.sleep(1000);
	           
	            //检测登录
	            NetQrPCEntity pc = netQrVo.getNetQrPCEntityMap().get(sessionid);
	    		if(pc!=null&&pc.getShow().equals("self")){//本人联网后提示
	    			sendJson.put("code",1);
	    			sendJson.put("show",1);
	    			fig = true;
	    			break;
	            }else if(pc!=null&&pc.getShow().equals("other")){//让别人上网操作
	            	sendJson.put("code", 1);
	    			sendJson.put("show", 2);
	    			fig = true;
	    			break;
	            }if(new Date().getTime() - inTime >4000){
	              bool = false;
	            }
	        }
	        if(!fig){//未取到缓存
	        	sendJson.put("code",0);
	        }
	        //删除缓存超时数据
	        netQrVo.Mapdelete(netQrVo.getNetQrPCEntityMap());
		 }catch (Exception e) {
			 sendJson.put("code",-1);
			 e.printStackTrace();
         }
        //发送
        out.print(sendJson);
        Log4gUtil.getLog().info("checkNetQr-输出PC二维码扫描检查登录-数据:"+sendJson.toString());
	}
	
	
	
	public void pcPassQR(){
		if(params!=null&&!params.equals("")){
			org.json.JSONObject dataParser = DataUtil.dataParser(params);
			if(dataParser.has("sessionid"))
				sessionid =  dataParser.getString("sessionid");
		}
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out =null;
		net.sf.json.JSONObject send = DataUtil.sendJson();
		try {
			out = response.getWriter();
			NetQrVo netQrVo = NetQrVo.getNetQrVo();
			netQrVo.getUuidMap().put(sessionid, "pass");
			send.put("code", 1);
		} catch (IOException e) {
			send.put("code", -1);
			e.printStackTrace();
		}
		out.print(send);
	}
	
	/**
	 * 本人联网操作  >Nf047
	 */
	public void pcQrselfNet(){
		if(params!=null&&!params.equals("")){
			org.json.JSONObject dataParser = DataUtil.dataParser(params);
			if(dataParser.has("userid"))
				userid = dataParser.getInt("userid");
			if(dataParser.has("sessionid"))
				sessionid =  dataParser.getString("sessionid");
			if(dataParser.has("apMac"))
				apMac =  dataParser.getString("apMac");
			if(dataParser.has("planTime"))
				planTime =  dataParser.getInt("planTime");
		}
		Log4gUtil.Info("pcQrselfNet-PC二维码本人连网授权", userid+"", "进入params", params, NF_callid, token);
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out =null;
		net.sf.json.JSONObject sendJson = DataUtil.sendJson();
		NetQrVo netQrVo = NetQrVo.getNetQrVo();
		NetQrPCEntity pc = netQrVo.getNetQrPCEntityMap().get(sessionid);
		try {
			out = response.getWriter();
			if(pc!=null){//缓存存在
				Log4gUtil.Info("pcQrselfNet-PC二维码本人连网授权", userid+"", "pc", pc.toString(), NF_callid, token);
				Userinfo  userinfo = userinfoService.selectUserinfo(userid);//用户信息
				Area siteArea = Verify.getArea(pc.getSiteAreaid(), areaService);//区域信息
					NetConnect netConnect = new NetConnect(0,0,0,0,0);
					//经过内网, 区域Id可用,并用户存在 
					//账号
					List<Useraccount> accounts = useraccountService.selectUseraccounts(userinfo.getUsers().getId(), 1);
					siteAreaid =pc.getSiteAreaid();
					ip = pc.getIp();
					mac = pc.getMac();
					
					NET nets = new NET();
					if(siteAreaid!=0&&(siteArea = Verify.getArea(siteAreaid, areaService)) != null&&
						(userinfo = userinfoService.selectUserinfo(userid)) != null&&!accounts.isEmpty()){
						//公网ip地址
						String gateIp = areaIpService.selectAreaip(siteAreaid).getPublicIp();
						//连网 || 检查权限
						netConnect.getNetConnect(userinfo, siteArea, ip, gateIp, mac,accounts.get(0).getAccount(),2,comboService, 
								areainfoService, bindingService, areausbleService,userinfoService,dealService,NF_callid,token,
								apMac,mapService,netLinkService);
						
						sendJson.put("code",1);
						
						Log4gUtil.Info("pcQrselfNet-PC二维码本人连网授权", userid+"", "netConnect.connect:"+netConnect.connect,
								"netConnect.vipHimt:"+netConnect.vipHimt, NF_callid, token);
						
						if(netConnect.connect==2){
							if(netConnect.vipHimt > 0 && planTime > 0){
								String timeUtil = NetTimeUtil.getTimeUtil(new Date(),planTime);
								Balance bal = dealService.selectBalance(userid);
								int longtime = bal.getLongTime();
								if(bal.getTicket04()!=null&&bal.getTicket04()>0){
									longtime = bal.getTicket04()+bal.getLongTime();
								}
								if(longtime>=0){
									netConnect.connect = nets.netAllow("","", siteAreaid, ip, 8,siteArea.getNetOnline(),
											timeUtil, gateIp,userid, mac,accounts.get(0).getAccount(),5,2,NF_callid,token,
											apMac,"",mapService,areausbleService,netLinkService);
									if(netConnect.connect==1){
										Keeptime kee = dealService.selectKeeptime(userid, 5,2,siteAreaid);
										if(kee!=null){
											kee.setKeepTime(timeUtil);
											kee.setPlanTime(planTime);
											kee.setNetOrder(nets.netOrder);
											kee.setArea(siteArea);
											dealService.updateKeeptime(kee);
										}else{
											kee= new Keeptime();
											Users users = new Users();
											users.setId(userid);
											kee.setUsers(users);
											
											kee.setPlanTime(planTime);
											kee.setKeepType(5);
											kee.setKeepDevice(2);
											kee.setKeepTime(timeUtil);
											kee.setArea(siteArea);
											kee.setNetOrder(nets.netOrder);
											dealService.insertKeeptime(kee);
										}
										userinfo.setNetOnline(1);
										userinfo.setUserIp(ip);
										userinfo.setUserMac(mac);
										userinfoService.updateUserinfo(userinfo);
									}
								}else{
									sendJson.put("code", 0);
									sendJson.put("reason", 5);
									sendJson.put("msg", "余额不足");
								}
							}
						}
						
						sendJson.put("connect", netConnect.connect);
						
						if(netConnect.connect==1){
							pc.setShow("self");
							//修改缓存
							netQrVo.getNetQrPCEntityMap().put(sessionid, pc);
						}
				}else{
					sendJson.put("code",0);
					sendJson.put("reason", 3);
					sendJson.put("msg","数据有误");
				}
			}else{
				sendJson.put("code",0);
				sendJson.put("reason", 1);
				sendJson.put("msg","二维码失效,请刷新");
			}
		} catch (Exception e) {
			Log4gUtil.getLog().info("pcQrnetworking:异常");
			sendJson.put("code",-1);
		}
		out.print(sendJson);
		Log4gUtil.Info("pcQrselfNet-PC二维码本人连网授权", userid+"", "输出", sendJson.toString(), sendJson.toString(), token);
	}
	
	/**
	 * 
	 * 别人连网标记  >Nf048
	 */
	public void pcQrotherNet(){
		
		if(params!=null&&!params.equals("")){
			org.json.JSONObject dataParser = DataUtil.dataParser(params);
			if(dataParser.has("userid"))
				userid = dataParser.getInt("userid");
			if(dataParser.has("sessionid"))
				sessionid =  dataParser.getString("sessionid");
			
		}
		Log4gUtil.Info("pcQrotherNet-PC二维码别人连网授权", userid+"", "进入params", params, NF_callid, token);
		
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out =null;
		net.sf.json.JSONObject sendJson = DataUtil.sendJson();
		
		Binding binding=null;//用户绑定信息
		Comboinfo comboinfo= null;//用户套餐信息
		VerifyResou verifre = new VerifyResou();
		NetQrVo netQrVo = NetQrVo.getNetQrVo();
		NetQrPCEntity pc = netQrVo.getNetQrPCEntityMap().get(sessionid);
		
		int band = 0;
		String netTime = null;
		
		try {
			out = response.getWriter();
			List<Useraccount> uc = useraccountService.selectUseraccounts(userid, 1);//用户账号信息
			Userinfo  userinfo = userinfoService.selectUserinfo(userid);//用户信息
			if(pc!=null){//缓存存在
				Area siteArea = Verify.getArea(pc.getSiteAreaid(), areaService);//区域信息
				if(userinfo!= null&&siteArea!= null&&!uc.isEmpty()){
					//绑定资源
					if((binding=verifre.verifyBinding(userid,pc.getSiteAreaid(), areausbleService, bindingService))!=null){
						if(binding.getArea().getId()==1&&binding.getTypeExplain()!=null
								&&binding.getTypeExplain().equals("老师")){
							netTime = NetTimeUtil.getTimeUtil(new Date(),1440);
						}else if(binding.getArea().getId()==1&&binding.getTypeExplain()!=null
								&&binding.getTypeExplain().equals("学生")){
							netTime = NetTimeUtil.getTimeUtil(new Date(),120);
						}else{
							netTime = NetTimeUtil.getTimeUtil(new Date(),120);
						}
						band = binding.getAreainfo().getAreatype().getBanfwidth();
					}/*else//套餐资源
						if((comboinfo=verifre.verifyCombo(userid, pc.getSiteAreaid(), areainfoService ,comboService))!=null){
						//套餐待定
					}*/
					if(band!=0){
						sendJson.put("code",1);
						pc.setShow("other");
						pc.setBand(band);
						pc.setTimeing(netTime);
						//修改缓存
						netQrVo.getNetQrPCEntityMap().put(sessionid, pc);
					}else{
						sendJson.put("code",0);
						sendJson.put("reason", 2);
						sendJson.put("msg","无资源");
					}
				}else{
					sendJson.put("code",0);
					sendJson.put("reason", 3);
					sendJson.put("msg","数据有误");
				}
			}else{
				sendJson.put("code",0);
				sendJson.put("reason", 1);
				sendJson.put("msg","缓存不存在");
			}
		} catch (Exception e) {
			Log4gUtil.getLog().info("pcQrnetworking:异常");
		}
		out.print(sendJson);
		Log4gUtil.Info("pcQrotherNet-输出PC二维码别人连网授权", userid+"", "输出", sendJson.toString(), sendJson.toString(), token);
	}
	/**
	 * 
	 * 别人连网操作  >Nf049
	 */
	public void otherNet(){
		
		if(params!=null&&!params.equals("")){
			org.json.JSONObject dataParser = DataUtil.dataParser(params);
			if(dataParser.has("userid"))
				userid = dataParser.getInt("userid");
			if(dataParser.has("sessionid"))
				sessionid =  dataParser.getString("sessionid");
			
		}
		
		Log4gUtil.Info("otherNet-PC二维码别人连网操作", userid+"", "进入params", params, NF_callid, token);
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out =null;
		net.sf.json.JSONObject sendJson = DataUtil.sendJson();
		NetQrVo netQrVo = NetQrVo.getNetQrVo();
		NetQrPCEntity pc = netQrVo.getNetQrPCEntityMap().get(sessionid);
		try {
			NET nets = new NET();
			out = response.getWriter();
			if(pc!=null&&pc.getBand() != 0){//缓存存在
				List<Useraccount> uc = useraccountService.selectUseraccounts(userid, 1);//用户账号信息
				Userinfo  userinfo = userinfoService.selectUserinfo(userid);//用户信息
				Area siteArea = Verify.getArea(pc.getSiteAreaid(), areaService);//区域信息
				if(userinfo!= null&&siteArea!= null&&!uc.isEmpty()){
					Areaip areaip = areaIpService.selectAreaip(pc.getSiteAreaid());
					int netAllow = nets.netAllow("", "", pc.getSiteAreaid(),pc.getIp(), pc.getBand(), siteArea.getNetOnline(),
							pc.getTimeing(), areaip.getPublicIp(),userid,pc.getMac(),uc.get(0).getAccount(),2,2,NF_callid,token,
							apMac,"",mapService,areausbleService,netLinkService);
					if(netAllow==1){
						sendJson.put("code",1);
						sendJson.put("connect",netAllow);
					}else{
						sendJson.put("code",0);
						sendJson.put("reason",4);
						sendJson.put("msg","连网未成功");
					}
				}else{
					sendJson.put("code",0);
					sendJson.put("reason", 3);
					sendJson.put("msg","数据有误");
				}
			}else{
				sendJson.put("code",0);
				sendJson.put("reason", 1);
				sendJson.put("msg","缓存有误");
			}
		} catch (Exception e) {
			sendJson.put("code",-1);
			sendJson.put("msg","异常");
			Log4gUtil.getLog().info("pcQrnetworking:异常");
		}
		out.print(sendJson);
		Log4gUtil.Info("otherNet-PC二维码别人连网操作", userid+"", "输出", sendJson.toString(), NF_callid, token);
	}
	
	
	public void setParams(String params) {
		this.params = params;
	}
	public void setSiteAreaid(int siteAreaid) {
		this.siteAreaid = siteAreaid;
	}

	public void setSessionid(String sessionid) {
		this.sessionid = sessionid;
	}

	public void setMac(String mac) {
		this.mac = mac;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public void setUserid(int userid) {
		this.userid = userid;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}

	public void setUserinfoService(UserinfoService userinfoService) {
		this.userinfoService = userinfoService;
	}

	public void setComboService(ComboService comboService) {
		this.comboService = comboService;
	}

	public void setAreainfoService(AreainfoService areainfoService) {
		this.areainfoService = areainfoService;
	}

	public void setBindingService(BindingService bindingService) {
		this.bindingService = bindingService;
	}

	public void setAreausbleService(AreausbleService areausbleService) {
		this.areausbleService = areausbleService;
	}

	public void setAreaIpService(AreaIpService areaIpService) {
		this.areaIpService = areaIpService;
	}

	public void setUseraccountService(UseraccountService useraccountService) {
		this.useraccountService = useraccountService;
	}

	public void setNF_callid(String nF_callid) {
		NF_callid = nF_callid;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public void setNetLinkService(NetLinkService netLinkService) {
		this.netLinkService = netLinkService;
	}

	public void setMapService(MapService mapService) {
		this.mapService = mapService;
	}

	public void setApMac(String apMac) {
		this.apMac = apMac;
	}

	public void setDealService(DealService dealService) {
		this.dealService = dealService;
	}

	public void setPlanTime(Integer planTime) {
		this.planTime = planTime;
	}

	public void setPlanTime(int planTime) {
		this.planTime = planTime;
	}

	public void setQRType(String qRType) {
		QRType = qRType;
	}
	
}
